package com.ruoyi.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.entity.JrFile;
import com.ruoyi.entity.JrSecuritys;
import com.ruoyi.entity.vo.FileUploadVO;
import com.ruoyi.service.FilesService;
import com.zhishiku.filesystem.server.MinioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "FilesController   api")
@Slf4j
@RequestMapping("/api/files")
public class FilesController extends BaseController {
    @Autowired
    private FilesService fileService;

    @Autowired
    private MinioService minioService;

    @PutMapping("/{fileId}/renameFile")
    public AjaxResult renameFile(@PathVariable Long fileId, @RequestBody Map<String, String> request) {
        String newName = request.get("newName");
        if (StringUtils.isBlank(newName)) {
            return AjaxResult.error("新文件名不能为空");
        }

        try {
            int result = fileService.renameFile(fileId, newName);
            return result > 0 ? AjaxResult.success() : AjaxResult.error("重命名失败");
        } catch (ServiceException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @DeleteMapping("/{fileId}")
    public AjaxResult deleteFile(@PathVariable Long fileId) {
        System.out.println("FilesController文件删除：" +fileId);
        return toAjax(fileService.deleteFile(fileId));
    }

    @ApiOperation("密级下拉框")
    @GetMapping("/levels")
    public List<JrSecuritys> getSecurityLevels() {
        List<JrSecuritys> files = fileService.getFilesByCurrentUserSecurity();
        System.out.println("下拉------------------------ ： "+ files);
        return files;
    }

    @ApiOperation("OnlyOffice保存回调")
    @PostMapping("/callback")
    public ResponseEntity<Map<String, Object>> handleCallback(
            @RequestBody Map<String, Object> payload,
            @RequestHeader(value = "Authorization", required = false) String token
    ) {

        // 2. 解析回调参数
        Map<String, Object> document = (Map<String, Object>) payload.get("document");
        String fileKey = (String) document.get("key");
        String downloadUrl = (String) payload.get("url");
        Integer status = (Integer) payload.get("status");

        // 3. 仅处理保存完成状态
        if (status != 2) {
            return ResponseEntity.ok(Collections.singletonMap("error", 0));
        }

        // 4. 解析文件ID和用户信息
        String[] parts = fileKey.split("_");
        Long fileId = Long.parseLong(parts[0]);
        Long userId = Long.parseLong(parts[1]);

        try {
            // 5. 下载新版本文件
            byte[] fileBytes = new RestTemplate().getForObject(downloadUrl, byte[].class);

            // 6. 更新文件记录
//            fileService.handleFileUpdate(fileId, userId, fileBytes);
            return ResponseEntity.ok(Collections.singletonMap("error", 0));
        } catch (Exception e) {
            log.error("文件更新失败：", e);
            return ResponseEntity.status(500).body(Collections.singletonMap("error", 1));
        }
    }

    @ApiOperation("上传文件2")
    @PostMapping(value = "/uploadNew", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult uploadFile(@RequestPart("files") MultipartFile[] files, // 必须使用@RequestPart
                                 @RequestPart("dto") FileUploadVO dto) {
        System.out.println(">>>> 上传文件2接口被调用 <<<<");
        dto.setFolderId(dto.getFolderId());
        dto.setSecurity(dto.getSecurity());
        dto.setHandleType(dto.getHandleType());
        return fileService.uploadFile(files,dto);
    }

    @GetMapping("/download/{fileId}")
    public void downloadFile(@PathVariable Long fileId, HttpServletResponse response) {
        JrFile file = fileService.getById(fileId);
        try (InputStream is = minioService.getFile(file.getFilePath())) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            IOUtils.copy(is, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败");
        }
    }
}
